/**
 * 总分类账查询 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.AccQuery.GlMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    permission: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 100,
        header: false,
        collapsible: true,
        collapseMode: "mini",
        border: 0,
        layout: {
          type: "table",
          columns: 5
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [{
          region: "west",
          width: 250,
          border: 1,
          split: true,
          layout: "fit",
          items: me.getSubjectGrid(),
        }, {
          region: "center",
          border: 1,
          layout: "fit",
          items: me.getMainGrid(),
        }]
      }]
    });

    me.callParent(arguments);

    me.editQueryOrg = PCL.getCmp(me.buildId(me, "editQueryOrg"));
    me.editQueryPeriodYear = PCL.getCmp(me.buildId(me, "editQueryPeriodYear"));
    me.editQueryPeriodMonth = PCL.getCmp(me.buildId(me, "editQueryPeriodMonth"));
    me.editQuerySubject = PCL.getCmp(me.buildId(me, "editQuerySubject"));

    me.panelQueryCmp = PCL.getCmp(me.buildId(me, "panelQueryCmp"));

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "Q",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }
        me.editQuerySubject.focus();
      },
      scope: me
    }, {
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = me.panelQueryCmp;
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.queryCompanyList();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [];
    let list = [];

    // 指南
    // 关闭
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("/Home/Help/index?t=accQuery"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getShortcutCmp());

    return result;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * 查询条件
   * 
   * @private
   */
  getQueryCmp() {
    const me = this;

    const modelName = me.buildModelName(me, "QueryOrg");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:18px;color:#595959;display:inline-block'>总分类账查询</h2>
                &nbsp;&nbsp;<span style='color:#8c8c8c'>总分类账账簿查询</span>
                <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>
                `
    }, {
      id: me.buildId(me, "editQueryOrg"),
      labelWidth: 70,
      width: 490,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "组织机构",
      margin: "10, 0, 0, 0",
      xtype: "combobox",
      queryMode: "local",
      editable: false,
      valueField: "id",
      displayField: "name",
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        },
        select: {
          fn: me._onComboOrgSelect,
          scope: me
        },
      },
      colspan: 4,
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQueryPeriod"),
      labelWidth: 70,
      width: 320,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "会计期间",
      margin: "5, 0, 0, 0",
      xtype: "fieldcontainer",
      layout: "hbox",
      items: [
        {
          xtype: "numberfield",
          hideTrigger: true,
          allowDecimals: false,
          width: 40,
          value: (new Date()).getFullYear(),
          id: me.buildId(me, "editQueryPeriodYear"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, { xtype: "displayfield", value: "年", width: 15, }, {
          xtype: "combobox",
          width: 70,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1, "一月"], [2, "二月"],
            [3, "三月"], [4, "四月"],
            [5, "五月"], [6, "六月"],
            [7, "七月"], [8, "八月"],
            [9, "九月"], [10, "十月"],
            [11, "十一月"], [12, "十二月"]]
          }),
          valueField: "id",
          displayFIeld: "text",
          queryMode: "local",
          editable: false,
          value: (new Date()).getMonth() + 1,
          id: me.buildId(me, "editQueryPeriodMonth"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          xtype: "button",
          text: "上一月",
          margin: "0 0 0 5",
          handler: me._onPriorMonth,
          scope: me,
        }, {
          xtype: "button",
          text: "下一月",
          handler: me._onNextMonth,
          scope: me,
        }
      ],
    }, {
      id: me.buildId(me, "editQuerySubject"),
      labelWidth: 120,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "会计科目码 <span class='PSI-shortcut-DS'>Alt + Q</span>",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onLastEditSpecialKey,
          scope: me
        }
      }
    }, {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5 0 0 10",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "清空查询条件",
        cls: "PSI-Query-btn2",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 10",
        handler: me._onClearQuery,
        scope: me
      }, {
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          me.panelQueryCmp.collapse();
        },
        scope: me
      }]
    },];
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editQueryOrg.getStore();
    const r = {
      url: me.URL("SLN0002/AccQuery/companyListForGL"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            const companyId = data[0]["id"];
            me.editQueryOrg.setValue(companyId);

            me.querySubjectList();
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  getSubjectGrid() {
    const me = this;

    if (me._subjectGrid) {
      return me._subjectGrid;
    }

    const modelName = me.buildModelName(me, "SubjectGrid");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._subjectGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      border: 0,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [{
          header: "科目码",
          dataIndex: "code"
        },
        {
          header: "科目名称",
          dataIndex: "name",
          width: 130,
        }]
      },
      store,
      listeners: {
        select: {
          fn: me._onSubjectGridSelect,
          scope: me
        },
      },
    });

    return me._subjectGrid;
  },

  /**
   * @private
   */
  querySubjectList() {
    const me = this;
    const companyId = me.editQueryOrg.getValue();
    const subjectCode = me.editQuerySubject.getValue();

    let id = null;
    const item = me.getSubjectGrid().getSelectionModel().getSelection();
    if (item?.length == 1) {
      id = item[0].get("id");
    }

    const store = me.getSubjectGrid().getStore();
    const r = {
      url: me.URL("SLN0002/AccQuery/subjectList"),
      params: {
        companyId,
        subjectCode,
      },
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          if (data.length > 0) {
            if (id) {
              const r = store.findExact("id", id);
              if (r != -1) {
                me.getSubjectGrid().getSelectionModel().select(r);
              }
            } else {
              me.getSubjectGrid().getSelectionModel().select(0);
            }
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  _onComboOrgSelect() {
    const me = this;

    me.querySubjectList();
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;

    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "AccGlData");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", "debit", "credit", "balance", "balanceDir", "voucherDT", "voucherSummary", "accFlag"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      border: 0,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "科目码",
          dataIndex: "code"
        }, {
          header: "科目名称",
          dataIndex: "name",
          width: 120,
        }, {
          header: "账务日期",
          dataIndex: "voucherDT",
        }, {
          header: "借方金额",
          dataIndex: "debit",
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        }, {
          header: "贷方金额",
          dataIndex: "credit",
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        }, {
          header: "余额",
          dataIndex: "balance",
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        }, {
          header: "余额方向",
          dataIndex: "balanceDir",
        }, {
          header: "摘要",
          dataIndex: "voucherSummary",
          width: 400,
          renderer(value, metaData, record) {
            const accFlag = parseInt(record.get("accFlag"))
            if (accFlag == 1000) {
              return `<span style='color:#006d75'>${value}</span>`;
            } else if (accFlag == 2000) {
              return `<span style='color:#006d75'>${value}</span>`;
            } else if (accFlag == 2001) {
              return `<strong style='color:#006d75'>${value}</strong>`;
            } else if (accFlag == 2002) {
              return `<strong style='color:#006d75'>${value}</strong>`;

            } else {
              return value;
            }
          }
        }]
      },
      store,
    });

    return me._mainGrid;
  },

  /**
   * @private
   */
  queryAccGlData() {
    const me = this;

    const item = me.getSubjectGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const subjectCode = item[0].get("code");

    const companyId = me.editQueryOrg.getValue();
    const year = me.editQueryPeriodYear.getValue();
    const month = me.editQueryPeriodMonth.getValue();

    const store = me.getMainGrid().getStore();
    const el = me.getMainGrid().getEl();

    el?.mask(PSI.Const.LOADING);

    const r = {
      url: me.URL("SLN0002/AccQuery/queryAccGlData"),
      params: {
        companyId,
        subjectCode,
        year,
        month,
      },
      callback(options, success, response) {
        el?.unmask();
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            me.getMainGrid().getSelectionModel().select(0);
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  _onSubjectGridSelect() {
    const me = this;

    me.queryAccGlData();
  },

  /**
   * @private
   */
  _onClearQuery() {
    const me = this;

    me.editQuerySubject.setValue(null);

    me._onQuery();
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    me.querySubjectList();
  },

  /**
   * @private
   */
  _onPriorMonth() {
    const me = this;

    let year = me.editQueryPeriodYear.getValue();
    let month = me.editQueryPeriodMonth.getValue();
    month--;
    if (month == 0) {
      year--;
      month = 12;
    }

    me.editQueryPeriodYear.setValue(year);
    me.editQueryPeriodMonth.setValue(month);

    me.queryAccGlData();
  },

  /**
   * @private
   */
  _onNextMonth() {
    const me = this;

    let year = me.editQueryPeriodYear.getValue();
    let month = me.editQueryPeriodMonth.getValue();
    month++;
    if (month == 13) {
      year++;
      month = 1;
    }

    me.editQueryPeriodYear.setValue(year);
    me.editQueryPeriodMonth.setValue(month);

    me.queryAccGlData();
  }
});
